<template>
    <div class="tree-container">
        <!-- 左侧角色树形结构 -->
        <div class="tree-item">
            <span class="tree-title">角色:</span>
            <el-tree :data="treeData" :render-after-expand="false" style="width: 240px; margin-top: 10px;"
                @node-click="handleRoleNodeClick" class="custom-tree" />
        </div>
        <div class="tree-item">
            <span class="tree-title">权限菜单:</span>
            <!-- 绑定菜单树形数据到 el-tree -->
            <el-tree ref="treeRef" style="width: 400px; margin-top: 10px;" class="filter-tree custom-tree" :data="menuTreeData" :props="props"
                node-key="id" default-expand-all show-checkbox :filter-node-method="filterNode"
                @check-change="handleMenuNodeClick" />
        </div>
    </div>
    <el-button type="primary" class="submit-button" @click="submit">提交</el-button>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ElTree } from 'element-plus'
import {read,write} from '@/axios/axiosHelper'

interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

// 定义用于存储角色树形结构数据的响应式变量
const treeData = ref<any[]>([])

// 分页信息
const getrolepage = ref({
    pageIndex: 1,
    pageSize: 100
})

// 存储点击的角色节点 id
const clickedRoleId = ref<number | null>(null)

// 角色数据
const getroleList = ref<any[]>([])

// 获取角色数据的方法
const GetRole = () => {
    read.get('/read/api/Role/GetRole2', {
        params: {
            pageIndex: getrolepage.value.pageIndex,
            pageSize: getrolepage.value.pageSize
        }
    })
        .then((res) => {
            const roleData = res.data.data || []
            const processedData = roleData.map((role: { roleId: string | number, roleName: string }) => ({
                value: role.roleId,
                label: role.roleName,
                children: []
            }))
            treeData.value = processedData
            getroleList.value = roleData
        })
        .catch((error) => {
            ElMessage.error('获取角色数据失败，请稍后重试')
            console.error('获取角色数据失败:', error)
        })
}

// 定义 el-tree 的 props
const props = {
    id: 'id',
    label: 'menuName',
    children: 'children',
};

// 定义用于存储菜单树形结构数据的响应式变量
const menuTreeData = ref([
    {
        id: 0,
        menuName: '菜单',
        children: []
    }
])

// 存储点击的菜单节点 id，改为数组类型
const clickedMenuIds = ref<number[]>([])

// 获取菜单数据的方法
const getMenu = async () => {
    try {
        const res = await read.get('/read/api/Main/GetMenuCascade')
        menuTreeData.value[0].children = res.data.data
        console.log('菜单数据:', menuTreeData.value)
    } catch (error) {
        ElMessage.error('获取菜单数据失败，请稍后重试')
        console.error('获取菜单数据失败:', error)
    }
}

// 处理角色节点点击事件
const handleRoleNodeClick = (data: { value: number }) => {
    clickedRoleId.value = data.value
    console.log('点击的角色 id:', clickedRoleId.value)
    Backfillroles(clickedRoleId)
}

// 处理菜单节点点击事件
const handleMenuNodeClick = () => {
    if (treeRef.value) {
        const checkedNodes = treeRef.value.getCheckedNodes(false, false);
        clickedMenuIds.value = checkedNodes.map(node => node.id);
    }
}

const submit = () => {
    console.log("点击的角色 id", clickedRoleId.value)
    console.log("点击的菜单 id 列表", clickedMenuIds.value)
    write.post('/write/api/RoleMenu/Handle', {
        roleId: clickedRoleId.value,
        menuId: clickedMenuIds.value
    })
        .then((res) => {
            if (res.data.code === 200) {
                ElMessage.success('添加成功')
            } else {
                ElMessage.error('添加角色菜单失败')
            }
        })
}

// 存放反填权限的值
const Backfillroleslist = ref<any[]>([])
// 反填方法
const Backfillroles = (clickedRoleId: any) => {
    read.get('/read/api/Main/AdditiveRole', {
        params: { roleId: clickedRoleId.value }
    })
        .then((res) => {
            Backfillroleslist.value = res.data.data;
            nextTick(() => { // 使用 nextTick 回调
                if (treeRef.value) {
                    const checkedIds = Backfillroleslist.value.map(item => item.id);
                    treeRef.value.setCheckedKeys(checkedIds);
                }
            });
        })
        .catch((error) => {
            ElMessage.error('获取角色权限失败');
            console.error(error);
        });
}

onMounted(() => {
    GetRole()
    getMenu()
})
</script>

<style scoped>
.tree-container {
    display: flex;
    align-items: flex-start;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tree-item {
    margin-right: 50px;
    background-color: #ffffff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
}

.tree-item:last-child {
    margin-right: 0; /* 去掉最后一个元素的右边距 */
}

.tree-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

.custom-tree {
    margin-top: 10px;
}

.submit-button {
    margin-top: 20px;
    width: 100px;
    font-weight: bold;
}
</style>